package com.probiz.estore.customer.dao.impl;

import java.util.Date;
import java.util.List;

import com.probiz.estore.common.model.customer.Favorite;
import com.probiz.estore.common.model.customer.FavoriteProduct;
import com.probiz.estore.common.model.customer.Favorite.FilterHqlName;
import com.probiz.estore.core.dao.impl.HibernateGenericDaoImpl;
import com.probiz.estore.customer.dao.FavoriteDao;

/**
 * Dao implementation for Favorite.
*/
@SuppressWarnings({ "unchecked", "serial" })
public class FavoriteDaoImpl extends HibernateGenericDaoImpl<Favorite> implements FavoriteDao {

	@Override
	protected void initFilterHqlMap() {
		filterHqlMap.put(FilterHqlName.DEFAULT, "select s from Favorite s");
		filterHqlMap.put(FilterHqlName.FOR_CUSTOMER, "select s from Favorite s where appuserId=? order by s.createTime desc");
	}
	
	public List<FavoriteProduct> getFavoriteProducts(Integer appuserId) {
		String hql = "from FavoriteProduct f where f.appuserId = ? ";
		return super.findByHql(hql, appuserId);
	}

	public List<Favorite> getFavorites(Integer appuserId) {
		String hql = "from Favorite f where f.appuserId = ? order by f.favoriteId asc";
		return super.findByHql(hql, appuserId);
	}

	public void addFavorite(Integer appuserId, Integer itemId, Short type) {
		String sql = "INSERT INTO FAVORITE(appuserId, itemId, type, createTime) VALUES (?, ?, ?, ?)";
		super.getSession(false).createSQLQuery(sql)
				.setInteger(0, appuserId)
				.setInteger(1, itemId)
				.setShort(2, type)
				.setTimestamp(3, new Date())
				.executeUpdate();
	}
	
	public void deleteFavoriteProducts(Integer productId) {
		String hql = "from FavoriteProduct f where f.product.productId = ? ";
		List<FavoriteProduct> list = super.findByHql(hql, productId);
		if (list != null) {
			for (FavoriteProduct favoriteProduct: list) {
				super.delete(favoriteProduct);
			}
		}
	}
	
	public List<Favorite> getFavoritesByCustomer(Integer appuserId, Integer maxSize){
		return this.find(" from Favorite f where f.appuserId = ?", 0, maxSize, appuserId);
	}

	public long countCustomerFavorite(Integer appuserId) {
		Long result = this.countByHql("select count(f) from Favorite f where f.appuserId = ?", appuserId);
		return result.longValue();
	}
	
}
